import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store';

Vue.use(VueRouter);

const router = new VueRouter({
  linkActiveClass: 'active',
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: () => import('@/components/Login.vue') },
    {
      path: '/index',
      component: () => import('@/components/Index.vue'),
      redirect: '/index/home',
      meta: { title: '后台' },
      children: [
        {
          path: 'home',
          name: 'home',
          component: () => import('@/components/Home.vue'),
          meta: { title: '首页' },
        },
        {
          path: 'books',
          name: 'books',
          component: () => import('@/components/Books.vue'),
          meta: { title: '图书管理' },
        },
        {
          path: 'bookstype',
          name: 'bookstype',
          component: () => import('@/components/BooksType.vue'),
          meta: { title: '分类列表' },
        },

        {
          path: 'user',
          name: 'user',
          component: () => import('@/components/User.vue'),
          redirect: 'user/checkpwd',
          meta: { title: '个人中心' },
          children: [
            {
              path: 'checkpwd',
              name: 'checkpwd',
              component: () => import('@/components/CheckPwd.vue'),
              meta: { title: '修改密码' },
            },
          ],
        },
      ],
    },
    {
      path: '*',
      component: () => import('@/components/NotFound.vue'),
    },
  ],
});
router.beforeEach((to, from, next) => {
  let token = store.state.token;
  if (to.path === '/login') {
    if (token) next('/index');
    else next();
  } else {
    // 每次页面跳转执行，token或openId錯誤，均提示跳转到首页
    if (token) next();
    else next('/login');
  }
});
// 先保存原始的 VueRoute push方法的引用
const originPush = VueRouter.prototype.push;
const originReplace = VueRouter.prototype.replace;

// 后重写
VueRouter.prototype.push = function (location, okCallback, failCallback) {
  if (okCallback && failCallback) {
    return originPush.call(this, location, okCallback, failCallback);
  } else {
    return originPush.call(this, location).catch(() => {});
  }
};

VueRouter.prototype.replace = function (location, okCallback, failCallback) {
  if (okCallback && failCallback) {
    return originReplace.call(this, location, okCallback, failCallback);
  } else {
    return originReplace.call(this, location).catch(() => {});
  }
};
export default router;
